package com.yxkj.syh.app.huarong.activities;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.immersionbar.ImmersionBar;
import com.syh.app.basic.base.BaseActivity;
import com.syh.app.basic.base.BaseFragment;
import com.syh.app.basic.bean.LiveDataEvent;
import com.syh.app.basic.config.BasicConstants;
import com.syh.app.basic.utils.ActivityManager;
import com.syh.app.basic.utils.Loog;
import com.syh.app.basic.utils.Tooast;
import com.yxkj.syh.app.huarong.activities.msg.MsgListActivity;
import com.yxkj.syh.app.huarong.activities.orders.OrdersFragment;
import com.yxkj.syh.app.huarong.activities.orders.list.OrderListFragment;
import com.yxkj.syh.app.huarong.activities.workbench.WorkbenchFragment;
import com.yxkj.syh.app.huarong.BR;
import com.yxkj.syh.app.huarong.R;
import com.yxkj.syh.app.huarong.constants.ArouterPath;
import com.yxkj.syh.app.huarong.databinding.ActivityMainBinding;
import com.yxkj.syh.app.huarong.util.UserManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

@Route(path = ArouterPath.MAIN_ACTIVITY)
public class MainActivity extends BaseActivity<ActivityMainBinding, MainVM> {

    String[] titles = new String[]{"工作台", "订单"};

    private WorkbenchFragment mWorkbenchFragment;
    private OrdersFragment mOrdersFragment;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected int getViewModelId() {
        return BR.mainVM;
    }

    @Override
    protected boolean needImmersionBarInit() {
        ImmersionBar.with(this).fitsSystemWindows(true).statusBarDarkFont(true).statusBarColor(R.color.defaultBlue).init();
        return false;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mWorkbenchFragment = WorkbenchFragment.newInstance();
        mOrdersFragment = OrdersFragment.newInstance();

        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(mWorkbenchFragment);
        fragments.add(mOrdersFragment);
        mVDBinding.stbMenu.setViewPager(mVDBinding.vpModule, titles, this, fragments);

        mVDBinding.flSetting.setOnClickListener(v -> {
            ARouter.getInstance().build(ArouterPath.SETTING_ACTIVITY).navigation();
        });
        mVDBinding.flMsg.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, MsgListActivity.class));
        });
    }

    @Override
    protected void initData() {
        super.initData();
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LiveDataEvent liveDataEvent) {
        switch (liveDataEvent.what) {
            case BasicConstants
                    .EVENT_LOGIN_STATUS:
                ARouter.getInstance().build(ArouterPath.LOGIN_ACTIVITY).navigation();
                ActivityManager.getInstance().finishAllActivity();
                break;
            case BasicConstants
                    .EVENT_SELECT_ORDER_ALL:
                requestedOrdersSelect = true;
                break;
        }
    }

    boolean requestedOrdersSelect = false;

    @Override
    protected void onResume() {
        super.onResume();
        if (UserManager.getUserManager().getUser() == null) {
            ARouter.getInstance().build(ArouterPath.LOGIN_ACTIVITY).navigation();
            finish();
        } else {

            setAlias();//极光的

            if (requestedOrdersSelect) {
                requestedOrdersSelect = false;
                if (mVDBinding.stbMenu.getCurrentTab() != 1) {
                    mVDBinding.stbMenu.setCurrentTab(1);
                }
            }
        }
    }

    long last;

    @Override
    public void onBackPressed() {
        long c = System.currentTimeMillis();
        if (c - last > 1000) {
            last = c;
            Tooast.normalInfo("双击退出");
        } else {
            ActivityManager.getInstance().finishAllActivity();
        }
    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }


    private void setAlias() {
//        JPushInterface.setAlias(App.getApplication(), 1, alias);
        // 调用 Handler 来异步设置别名
        if (UserManager.getUserManager().isSetedAlias()) {
            Loog.d("MainActivity", "用户" + UserManager.getUserManager().getUser().getRealName() + "," + UserManager.getUserManager().getUser().getId() + "已设置过Alias");
        } else {
            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS));
        }
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        String logs = "--";

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            switch (code) {
                case 0:
                    logs = "Set  alias success . alias = " + alias;
                    Log.i("MainActivity", logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    UserManager.getUserManager().setedAlias();
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 10s.";
                    Log.i("MainActivity", logs);
                    // 延迟 10 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS), 1000 * 10);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e("MainActivity", logs);
            }
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    if (UserManager.getUserManager().getUser() != null) {//这里再作判断  防止进入6002 循环

                        String alias = UserManager.getUserManager().getUser().getId() + "";

                        Loog.d("MainActivity", "Set alias in handler. msg.obj = " + alias);
                        // 调用 JPush 接口来设置别名。
                        JPushInterface.setAlias(getApplicationContext(),
                                alias,
                                mAliasCallback);
                    }
                    break;
                default:
                    Log.i("MainActivity", "Unhandled msg - " + msg.what);
            }
        }
    };
}
